package cn.gok.springsecuritydemo02.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.Console;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: chen fan
 * @since: 2022/11/17 16:41
 * @description:
 */
@Controller
public class LoginController {


    @RequestMapping("/toSuccessPage")
    public String toSuccessPage(){
        return "success";
    }

    @RequestMapping("/toFailPage")
    public String toFailPage(){
        return "fail";
    }


    @RequestMapping("/toLoginPage")
    public String toLoginPage(){
        return "login";
    }


    /**
     * 获取验证码，返回的是验证的路径
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/getValidateCode")
    public Map<String,Object> getValidateCode(HttpServletRequest request, HttpSession session){

        // 创建图片存放路径
        String path = LoginController.class.getClassLoader().getResource("static").getPath();
        File file = new File(path + "/temp/validateCode");
        if (!file.exists()){
            file.mkdirs();
        }
        //生成验证的图片名
        String validateCodeImageName =  UUID.randomUUID().toString() + ".png";
        //生成图片的输出地址
        StringBuffer stringBuffer = new StringBuffer(path + "/temp/validateCode/" + validateCodeImageName);
        ////定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 32, 4, 4);
        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(stringBuffer.toString());
        //获取code
        String code = captcha.getCode();
        //将验证码存放进缓存
        session.setAttribute("validateCode",code);
        //将验证码图片地址响应给前端
        Map<String, Object> result = new HashMap<>();
        result.put("code","200");
        result.put("imageUrl","/temp/validateCode/"+validateCodeImageName);
        return result;
    }
}
